package br.com.center.loja.ws;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import br.com.center.loja.data.NamedRepository;
import br.com.center.loja.data.RepositoryFactoryJPA;
import br.com.center.loja.model.Product;
import br.com.center.loja.ws.dto.ProductDTO;

@Path("/product")
public class ProductResource {
	
	@GET
	@Produces({MediaType.APPLICATION_JSON})
	public List<ProductDTO> all(){
		List<Product> all = RepositoryFactoryJPA.create(Product.class)
				                                .all();
		
		return convert(all);
	}

	@GET
	@Path("/search/name/{query}")
	@Produces({MediaType.APPLICATION_JSON})
	public List<ProductDTO> allByName(@PathParam("query") String name){
		NamedRepository<Product> repository = 
				RepositoryFactoryJPA.createNamed(Product.class);
		List<Product> all = repository.all(name);
		return convert(all);		
	}
	
	@GET
	@Path("/search/code/{query}")
	@Produces({MediaType.APPLICATION_JSON})
	public ProductDTO selectByCode(@PathParam("query") Long code){
		Product product = RepositoryFactoryJPA.create(Product.class)
				                              .select(code);
		
		return new ProductDTO(product);
	}
	
	private List<ProductDTO> convert(List<Product> products){
		List<ProductDTO> result = new ArrayList<ProductDTO>();
		
		for (Product product : products) {
			result.add(new ProductDTO(product));
		}
		
		return result;		
	}

}
